<template>
  <view class="outing-card">
    <!-- 上半部分：客户 & 原因 -->
    <view class="header">
      <text class="name">{{ record.customerName }}</text>
    </view>

    <!-- 陪同人 & 关系 -->
    <view class="info-row">
      <view class="info-item">
        <text class="label">陪同人：</text>
        <text class="value">{{ record.withWho }}</text>
      </view>
      <view class="info-item">
        <text class="label">关系：</text>
        <text class="value">{{ record.relationship }}</text>
      </view>
    </view>

    <!-- 外出时间 -->
    <view class="info-row">
      <view class="info-item full-width">
        <text class="label">外出时间：</text>
        <text class="value">{{ formatDate(record.outingDate) }}</text>
      </view>
    </view>

    <!-- 回院时间 + 按钮（根据是否已回院显示不同状态） -->
    <view class="info-row align-center">
      <view class="info-item full-width">
        <text class="label">回院时间：</text>
        <text class="value">{{ formatDate(displayedReturnDate) }}</text>
      </view>
      <button
        class="btn-register"
        :disabled="hasReturned"
        @tap.stop="toggleReturnPicker"
      >
        {{ hasReturned ? '已回院' : (showReturnPicker ? '取消' : '登记回院时间') }}
      </button>
    </view>

    <!-- 日期 & 时间 选择区，仅在未回院时可见 -->
    <view v-if="showReturnPicker && !hasReturned" class="picker-row">
      <picker mode="date" @change="onDateChange">
        <view class="picker-btn">{{ selectedDate || '选择日期' }}</view>
      </picker>
      <picker mode="time" @change="onTimeChange">
        <view class="picker-btn">{{ selectedTime || '选择时间' }}</view>
      </picker>
      <button class="btn-confirm" @tap="confirmReturn">确认</button>
    </view>

    <!-- 外出事由 -->
    <view class="info-row reason-row" v-if="record.reason">
      <view class="info-item full-width">
        <text class="label">外出事由：</text>
        <text class="value reason" @tap="toggleExpand">
          {{ displayReason }}
        </text>
      </view>
    </view>

    <!-- 紧急联系方式 -->
    <view class="emergency">
      <text class="emergency-label">紧急联系方式：</text>
      <text class="emergency-phone">{{ record.withWhoPhone }}</text>
    </view>
  </view>
</template>

<script>
import { updateOutingRecord } from '@/api/client';
export default {
  name: 'OutingRecordCard',
  props: {
    record: { type: Object, required: true }
  },
  data() {
    return {
      expanded: false,
      showReturnPicker: false,
      selectedDate: '',
      selectedTime: '',
      tempActualReturn: ''
    };
  },
  computed: {
    // 判断是否已经登记实际回院
    hasReturned() {
      return Boolean(this.record.actualReturnDate || this.tempActualReturn);
    },
    // 显示优先级：实际回院 > 临时值 > 预计回院
    displayedReturnDate() {
      return this.tempActualReturn || this.record.actualReturnDate || this.record.expectedReturnDate;
    },
    displayReason() {
      const txt = this.record.reason || '';
      if (this.expanded || txt.length <= 9) return txt;
      return txt.slice(0, 9) + '…';
    }
  },
  methods: {
    formatDate(dt) {
      if (!dt) return '';
      const d = new Date(dt);
      const pad = n => String(n).padStart(2, '0');
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ` +
             `${pad(d.getHours())}:${pad(d.getMinutes())}`;
    },

    toggleExpand() {
      this.expanded = !this.expanded;
    },

    toggleReturnPicker() {
		// 如果已回院，直接退出
		    if (this.hasReturned) return;

      this.showReturnPicker = !this.showReturnPicker;
      if (!this.showReturnPicker) {
        // 取消时重置
        this.selectedDate = '';
        this.selectedTime = '';
      }
    },

    onDateChange(e) {
      this.selectedDate = e.detail.value;
    },

    onTimeChange(e) {
      this.selectedTime = e.detail.value;
    },

    async confirmReturn() {
      if (!this.selectedDate || !this.selectedTime) {
        uni.showToast({ title: '请选择完整的日期和时间', icon: 'none' });
        return;
      }
      // 格式化为后端可识别的 ISO 格式 yyyy-MM-ddTHH:mm:00
      const datetime = `${this.selectedDate} ${this.selectedTime}:00`;
      try {
        await updateOutingRecord({ outingId: this.record.outingId, actualReturnDate: datetime });
        this.tempActualReturn = datetime;
        uni.showToast({ title: '回院时间已更新' });
        this.showReturnPicker = false;
      } catch (err) {
        uni.showToast({ title: '更新失败，请重试', icon: 'none' });
      }
    }
  }
};
</script>

<style scoped>
.outing-card { background-color: #fafafa; border-radius: 12px; padding: 16px; margin: 12px 16px; box-shadow: 0 1px 4px rgba(0,0,0,0.1); }
.header { display: flex; align-items: center; margin-bottom: 12px; }
.name { font-size: 18px; font-weight: 600; color: #333; }
.info-row { display: flex; align-items: center; flex-wrap: wrap; margin-bottom: 8px; }
.info-row.align-center { justify-content: space-between; }
.info-item { flex: 1 1 50%; display: flex; margin-bottom: 4px; }
.info-item.full-width { flex: 1 1 auto; }
.label { font-size: 14px; color: #666; width: 80px; }
.value { font-size: 14px; color: #444; flex: 1; }
.picker-row { display: flex; align-items: center; margin-bottom: 8px; }
.picker-btn { padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; margin-right: 8px; }
.btn-confirm { background-color: #00c3b0; color: #fff; padding: 6px 12px; font-size: 14px; border-radius: 20px; line-height: 1; }
.reason-row .value.reason { white-space: normal; word-wrap: break-word; word-break: break-all; line-height: 1.4em; max-height: 4.2em; overflow-y: auto; color: #00c3b0; }
.emergency { margin: 12px 0 0; padding: 8px; background-color: #fff4e5; border-left: 4px solid #ff9f1a; border-radius: 4px; display: flex; align-items: center; }
.emergency-label { font-size: 14px; color: #ff7000; margin-right: 4px; font-weight: 500; }
.emergency-phone { font-size: 14px; color: #d35400; font-weight: 600; }
.btn-register { background-color: #00c3b0; color: #fff; padding: 6px 12px; font-size: 14px; border-radius: 20px; line-height: 1; margin-left: 8px; }
.btn-register[disabled] { background-color: #ccc; }
</style>
